package com.cloudbroker.bcs.common.dao.base;

import com.cloudbroker.bcs.common.entity.Markable;
import com.cloudbroker.bcs.common.entity.Pageable;
import com.cloudbroker.bcs.common.model.SortMarker;

import java.lang.reflect.Field;

import static org.apache.ibatis.jdbc.SqlBuilder.*;
import static org.apache.ibatis.jdbc.SqlBuilder.ORDER_BY;

/**
 * Created by zhaosh19213 on 2016/9/14.
 */
public class CRUDTemplate<T extends Pageable> {
    private T obj;

    public CRUDTemplate(T obj) {
        this.obj = obj;
    }

    public CRUDTemplate(Object obj) {
        if (obj instanceof MyBatisPojo) {
            this.obj = (T) obj;
        }else{
            this.obj = null;
        }
    }

    public String insert() throws NoSuchFieldException, IllegalAccessException {
        BEGIN();

        INSERT_INTO(obj.tablename());
        obj.caculationColumnList();

        VALUES(obj.returnInsertColumnsName(), obj.returnInsertColumnsDefine());

        return SQL();
    }

    public String update() throws NoSuchFieldException, IllegalAccessException {
        String idname = obj.primaryKey();
        BEGIN();

        UPDATE(obj.tablename());
        obj.caculationColumnList();
        SET(obj.returnUpdateSet());
        WHERE(idname + "='" + obj.primaryKeyValue() + "'");

        return SQL();
    }

    public String delete() throws IllegalAccessException {
        String idname = obj.primaryKey();

        BEGIN();

        DELETE_FROM(obj.tablename());
        WHERE(idname + "='" + obj.primaryKeyValue() + "'");

        return SQL();
    }

    public String get() throws IllegalAccessException {
        String idname = obj.primaryKey();

        BEGIN();
        obj.caculationColumnList();
        SELECT(obj.returnAllColumnsName());
        FROM(obj.tablename());
        if (obj.returnWhereColumns()!=null &&obj.returnWhereColumns().length()>0)
            WHERE(obj.returnWhereColumns());
        if (obj instanceof Pageable && obj.getSortMarkers() != null) {
            for (SortMarker sortMarker : obj.getSortMarkers()){
                ORDER_BY(sortMarker.getField() + " " + sortMarker.getDirection());
            }
        }else {
            ORDER_BY(obj.primaryKey() + " DESC");
        }
        if (obj instanceof Pageable && obj.getPage() != null) {
            Integer page_size = obj.getPage().getPage_size();
            Integer page_no = obj.getPage().getPage_no();
            Integer startRow = (page_no>0?(page_no-1):0)*10;
            return SQL() + " limit " + startRow + "," + page_size;
        }
        return SQL();
    }

}
